<?php

namespace app\push\controller;
ignore_user_abort(true);
set_time_limit (0);
error_reporting(E_ALL ^ E_NOTICE);
ob_implicit_flush();
use Workerman\Worker;
use think\Db;
class Socket
{
    public function index()
    {
        //Vendor('workerman.Worker');//调用类库,路径是基于vendor文件夹的
		// 创建一个Worker监听2346端口，使用websocket协议通讯
		$ws_worker = new Worker("websocket://0.0.0.0:10101");
		// 启动4个进程对外提供服务
		$ws_worker->count = 1;
		
		// 当收到客户端发来的数据后返回hello $data给客户端
		$ws_worker->onMessage = function($connection, $data)
		{
		    global $ws_worker;
		    //db('socket')->insert(['name'=>'asdasd11','value'=>$data]);
		    //$worker_id = $ws_worker->id;
		    //db('socket')->insert(['name'=>'asdasd22','value'=>$worker_id]);
		    // 向客户端发送hello $data
		    //$this->send($worker_id,$data,$connection);
		    //$connection->send('hello ' . $data);
		    //向客户端回发数据
		   // if(!isset($connection->uid))
		    //{
		        // 没验证的话把第一个包当做uid（这里为了方便演示，没做真正的验证）
		        $connection->uid = uniqid();
		        /* 保存uid到connection的映射，这样可以方便的通过uid查找connection，
		         * 实现针对特定uid推送数据
		         */
		        //db('socket')->insert(['name'=>'asdasd22','value'=>$connection->uid]);
		        $ws_worker->uidConnections[$connection->uid] = $connection;
		        return $this->send($connection->uid,$data,$connection);
		        //$connection->send('login success, your uid is ' . $connection->uid);
		   // }
		    // uid 为 all 时是全局广播
		    /* list($recv_uid, $message) = explode(':', $data);
		    // 全局广播
		    if($recv_uid == 'all')
		    {
		        broadcast($message);
		    }
		    // 给特定uid发送
		    else
		    {
		        sendMessageByUid($recv_uid, $message);
		    } */
		};  
        
		// 运行worker
		Worker::runAll();
		//db('socket')->insert(['name'=>'asdasd']);
    }
    // 向所有验证的用户推送数据
    function broadcast($message)
    {
        global $ws_worker;
        foreach($ws_worker->uidConnections as $k=>$connection)
        {
            //echo '1/';
            $this->send($k,$message,$connection);
            //$connection->send($message);
        }
    }
    
    // 针对uid推送数据
    function sendMessageByUid($uid, $message)
    {
        global $ws_worker;
        if(isset($ws_worker->uidConnections[$uid]))
        {
            $connection = $ws_worker->uidConnections[$uid];
            $this->send($uid,$message,$connection);
            //$connection->send($message);
        }
    }
    public function send1($k,$ar,$key='',$connection){
        global $ws_worker;
        $connection->send(json_encode($ar));
        if(!empty($key)){
            $connection1 = $ws_worker->uidConnections[$key];
            $connection1->send(json_encode($ar));
        }
        
    }
    //用户加入或client发送信息
    public function send($k,$msg,$connection){
        //将查询字符串解析到第二个参数变量中，以数组的形式保存如：parse_str("name=Bill&age=60",$arr)
        parse_str($msg,$g);
    
        /*if($g['type']=='add'){
         //第一次进入添加聊天名字，把姓名保存在相应的users里面
         $this->users[$k]['name']=$g['ming'];
         $ar['type']='add';
         $ar['name']=$g['ming'];
         $key='all';
         } else{
         $key=$g['key'];
         $ar['nrong']=$g['nr'];
         $key=$g['key'];
        } */
        if($g['type']=='import'){
            $this->import($k,$g,$connection);
        }elseif($g['type']=='play_in'){
            $this->play_in($k,$g,$connection);
        }elseif($g['type']=='play_fight'){
            $this->play_fight($k,$g,$connection);
        }elseif($g['type']=='play_dati'){
            $this->play_dati($k,$g,$connection);
        }elseif($g['type']=='play_over'){
            $this->play_over($k,$g,$connection);
        }
        else{
            //推送信息
            $this->send1($k,$ar,$connection);
        }
    
    }
    function play_over($k,$ar,$connection){
        $uid = $ar['uid'];
        if(!empty($uid)){
            if(!empty($ar['house_id'])){
                $house_id = $ar['house_id'];
                $house = db('question_house')->where("(uid1=$uid or uid2=$uid)")->where('id',$house_id)->where('status',2)->find();
    
            }else{
                $house = db('question_house')->where("(uid1=$uid or uid2=$uid)")->where('status',2)->order('id','desc')->limit(1)->find();
            }
            if(empty($house)){
                $ar['type'] = 'error';
                $this->send1($k,$ar,'',$connection);
            }else{
                $house_id = $house['id'];
                $ar['house'] = $house;
                $uid1_snum = db('question_log')->where('house_id',$house_id)->where('uid1_answer=answer')->count();
                $uid2_snum = db('question_log')->where('house_id',$house_id)->where('uid2_answer=answer')->count();
                $ar['uid1_snum'] = $uid1_snum;
                $ar['uid2_snum'] = $uid2_snum;
                $uid1 = db('member')->where('id',$house['uid1'])->field('id,nickname,head')->find();
                $uid2 = db('member')->where('id',$house['uid2'])->field('id,nickname,head')->find();
                $ar['uid1'] = $uid1;
                $ar['uid2'] = $uid2;
                $this->send1($k,$ar,'',$connection);
            }
        }
    }
    function play_fight($k,$ar,$connection){
        $uid = $ar['uid'];
        $house_id = $ar['house_id'];
        if(!empty($house_id)){
            $house = db('question_house')->where('id',$house_id)->find();
            if($house['uid1']==$uid){
                db('question_house')->where('id',$house_id)->update(['uid1_key'=>$k]);
                $key = $house['uid2_key'];
            }elseif($house['uid2']==$uid){
                db('question_house')->where('id',$house_id)->update(['uid2_key'=>$k]);
                $key = $house['uid1_key'];
            }
            //db('socket')->insert(['name'=>json_encode($house),'value'=>$key.'|'.$k]);
            if($house['status']==0){
                db('question_house')->where('id',$house_id)->update(['start_time'=>time(),'status'=>1,'question_sort'=>1]);
                $house['question_sort'] = 1;
                $house['start_time'] = time();
                $house['status'] = 1;
                $questions = db('question')->where('grade',$house['grade'])->select();
                $total = count($questions);
                $p = intval($total/10);$time = time();
                for($i=0;$i<10;$i++){
                    $min = $i*$p;
                    $max = ($i==9)?$total:($i+1)*$p;
                    $kaa = rand($min,$max);
                    $question = $questions[$kaa];
                    $sql = ['create_time'=>time(),'answer'=>$question['answer'],'content'=>$question['question'],'question_id'=>$question['id'],'house_id'=>$house_id];
                    //$sql['start_time'] = $time+$i*10;
                    $sql['sort'] = $i+1;
                    /*  if($i==0){
                     $sql['start_time'] = time();
                     $this_question = $question;
                     $this_question['question'] = unserialize($this_question['question']);
                     } */
                    db('question_log')->insert($sql);
                }
                $time = time();
                db('question_house')->where('id',$house_id)->update(['last_time'=>$time]);
                $this_question_log = db('question_log')->where('house_id',$house_id)->where('sort',1)->find();
                db('question_log')->where('id',$this_question_log['id'])->update(['start_time'=>$time]);
                $this_question_log['start_time'] = $time;
                $sort = 1;
            }elseif(!empty($ar['sort'])){
                $sort = $ar['sort'];
                $time = time();
                db('question_house')->where('id',$house_id)->update(['last_time'=>$time,'question_sort'=>$sort]);
                $this_question_log = db('question_log')->where('house_id',$house_id)->where('sort',$sort)->find();
                if(!empty($this_question_log['end_time'])||($time-$this_question_log['start_time']>10)){
                    $sort = $ar['sort']+1;
                    if($sort<=10){
                        db('question_house')->where('id',$house_id)->update(['last_time'=>$time,'question_sort'=>$sort]);
                        $this_question_log = db('question_log')->where('house_id',$house_id)->where('sort',$sort)->find();
                        db('question_log')->where('id',$this_question_log['id'])->update(['start_time'=>$time]);
                        $this_question_log['start_time'] = $time;
                    }
                }
    
            }else
            {
                $len_time = time()-$house['last_time'];
                $sort = intval($len_time/10)+$house['question_sort'];
                if($sort<=10){
                    $this_question_log = db('question_log')->where('house_id',$house_id)->where('sort',$sort)->find();
                    $stime = $house['last_time']+intval($len_time/10)*10;
                    db('question_house')->where('id',$house_id)->update(['last_time'=>$stime,'question_sort'=>$sort]);
                    db('question_log')->where('id',$this_question_log['id'])->update(['start_time'=>$stime]);
                    $this_question_log['start_time'] = $stime;
                }
    
    
            }
            //db('socket')->insert(['name'=>$sort,'value'=>'qq']);
            if($sort<=10){
                //for($j=$jj;$j<=10;$j++){
                //$this_question_log = db('question_log')->where('house_id',$house_id)->where('sort',$jj)->find();
                $this_question = db('question')->where('id',$this_question_log['question_id'])->find();
                $ar['question_log'] = $this_question_log;
                $this_question['question'] = unserialize($this_question['question']);
                $ar['question'] = $this_question;
                $uid1 = db('member')->where('id',$house['uid1'])->field('id,nickname,head')->find();
                $uid2 = db('member')->where('id',$house['uid2'])->field('id,nickname,head')->find();
                $ar['uid1'] = $uid1;
                $ar['uid2'] = $uid2;
                $now_house = db('question_house')->where('id',$house_id)->find();
                $ar['house'] = $now_house;
                $ar['nowTime'] = time();
                $this->send1($k,$ar,'',$connection);
                //sleep(10);
                //db('question_house')->where('id',$house_id)->update(['question_sort'=>$now_house['question_sort']+1]);
                // }
                //db('question_house')->where('id',$house_id)->update(['end_time'=>time(),'status'=>2,'question_sort'=>10]);
            }else{
                $ar['type'] = 'over';
                if($house['status']!=2){
                    db('question_house')->where('id',$house_id)->update(['status'=>2,'end_time'=>time()]);
                    $now_house = db('question_house')->where('id',$house_id)->find();
                    $reward = 0;
                    if($now_house['grade']==1){
                        $reward = db('config')->where('name','easy_in')->value('value');
                    }elseif($now_house['grade']==2){
                        $reward = db('config')->where('name','normal_in')->value('value');
                    }elseif($now_house['grade']==3){
                        $reward = db('config')->where('name','hard_in')->value('value');
                    }
                    if($now_house['uid1_score']>$now_house['uid2_score']){
                        db('question_house')->where('id',$house_id)->update(['reward_uid'=>$now_house['uid1'],'reward'=>$reward]);
                        db('member')->where('id',$now_house['uid1'])->setInc('reward_wallet',$reward);
                        db('wallet_bill')->insert(['uid'=>$now_house['uid1'],'count'=>$reward,'type'=>2,'category_id'=>7,'create_time'=>time()]);
                    }elseif($now_house['uid1_score']==$now_house['uid2_score']){
                        db('question_house')->where('id',$house_id)->update(['reward_uid'=>0,'reward'=>$reward/2]);
                        db('member')->where('id',$now_house['uid1'])->setInc('reward_wallet',$reward/2);
                        db('member')->where('id',$now_house['uid2'])->setInc('reward_wallet',$reward/2);
                        db('wallet_bill')->insert(['uid'=>$now_house['uid1'],'count'=>$reward/2,'type'=>2,'category_id'=>7,'create_time'=>time()]);
                        db('wallet_bill')->insert(['uid'=>$now_house['uid2'],'count'=>$reward/2,'type'=>2,'category_id'=>7,'create_time'=>time()]);
                    }elseif($now_house['uid1_score']<$now_house['uid2_score']){
                        db('question_house')->where('id',$house_id)->update(['reward_uid'=>$now_house['uid2'],'reward'=>$reward]);
                        db('member')->where('id',$now_house['uid2'])->setInc('reward_wallet',$reward);
                        db('wallet_bill')->insert(['uid'=>$now_house['uid2'],'count'=>$reward,'type'=>2,'category_id'=>7,'create_time'=>time()]);
                    }
                }
                $this->send1($k,$ar,$key,$connection);
            }
        }
    }
    function play_dati($k,$ar,$connection){
        $uid = $ar['uid'];
        $house_id = $ar['house_id'];
        $answer = $ar['answer'];
        $sort = $ar['sort'];$time = time();
        if(!empty($house_id)&&!empty($sort)&&!empty($uid)){
            $house = db('question_house')->where('id',$house_id)->find();
            $uid_sort = '';
            if($house['uid1']==$uid){
                db('question_house')->where('id',$house_id)->update(['uid1_key'=>$k]);
                $key = $house['uid2_key'];
                $uid_sort = 1;
            }elseif($house['uid2']==$uid){
                db('question_house')->where('id',$house_id)->update(['uid2_key'=>$k]);
                $key = $house['uid1_key'];
                $uid_sort = 2;
            }
    
            if($house['status']==1){
                $log = db('question_log')->where('house_id',$house_id)->where('sort',$sort)->find();
                $question = db('question')->where('id',$log['question_id'])->find();
                if($question['answer']==$answer){
                    $scroe = $this->scroe($time,$log['start_time'],$sort);
                    if($uid_sort==1){
                        db('question_house')->where('id',$house_id)->update(['uid1_score'=>$scroe+$house['uid1_score']]);
                    }elseif($uid_sort==2){
                        db('question_house')->where('id',$house_id)->update(['uid2_score'=>$scroe+$house['uid2_score']]);
                    }
                }
                if($uid_sort==1){
                    $sql_log = ['uid1_answer'=>$answer];
                    if($log['uid2_answer']>0){
                        $sql_log['end_time'] = $time;
                    }
                }elseif($uid_sort==2){
                    $sql_log = ['uid2_answer'=>$answer];
                    if($log['uid1_answer']>0){
                        $sql_log['end_time'] = $time;
                    }
                }
                db('question_log')->where('id',$log['id'])->update($sql_log);
                /* if(!empty($sql_log['end_time'])){
                 $sort = $ar['sort'] = $sort+1;
                 if($sort<=10){
                 $log = db('question_log')->where('house_id',$house_id)->where('sort',$sort)->find();
                 $question = db('question')->where('id',$log['question_id'])->find();
                 $question['question'] = unserialize($question['question']);
                 db('question_house')->where('id',$house_id)->update(['question_sort'=>$sort]);
                 $now_house = db('question_house')->where('id',$house_id)->find();
                 $ar['house'] = $now_house;$ar['question'] = $question;
                 $stop = 0;
                 $stime = time()+$stop;
                 db('question_log')->where('id',$log['id'])->update(['start_time'=>$stime]);
                 $log['start_time'] = $stime;
                 $ar['question_log'] = $log;
                 $ar['type'] = 'play_next';
                 //$ar['stop'] = $stop;
                 $uid1 = db('member')->where('id',$house['uid1'])->field('id,nickname,head')->find();
                 $uid2 = db('member')->where('id',$house['uid2'])->field('id,nickname,head')->find();
                 $ar['uid1'] = $uid1;
                 $ar['uid2'] = $uid2;
                 $this->send1($k,$ar,$key);
                 }else{
                 $ar['type'] = 'over';
                 db('question_house')->where('id',$house_id)->update(['status'=>2,'end_time'=>time()]);
                 $now_house = db('question_house')->where('id',$house_id)->find();
                 $reward = 0;
                 if($now_house['grade']==1){
                 $reward = db('config')->where('name','easy_in')->value('value');
                 }elseif($now_house['grade']==2){
                 $reward = db('config')->where('name','normal_in')->value('value');
                 }elseif($now_house['grade']==3){
                 $reward = db('config')->where('name','hard_in')->value('value');
                 }
                 if($now_house['uid1_score']>$now_house['uid2_score']){
                 db('member')->where('id',$now_house['uid1'])->setInc('lcc_wallet',$reward);
                 db('wallet_bill')->insert(['uid'=>$now_house['uid1'],'count'=>$reward,'type'=>2,'category_id'=>7,'create_time'=>time()]);
                 }elseif($now_house['uid1_score']==$now_house['uid2_score']){
                 db('member')->where('id',$now_house['uid1'])->setInc('lcc_wallet',$reward/2);
                 db('member')->where('id',$now_house['uid2'])->setInc('lcc_wallet',$reward/2);
                 db('wallet_bill')->insert(['uid'=>$now_house['uid1'],'count'=>$reward/2,'type'=>2,'category_id'=>7,'create_time'=>time()]);
                 db('wallet_bill')->insert(['uid'=>$now_house['uid2'],'count'=>$reward/2,'type'=>2,'category_id'=>7,'create_time'=>time()]);
                 }elseif($now_house['uid1_score']<$now_house['uid2_score']){
                 db('member')->where('id',$now_house['uid2'])->setInc('lcc_wallet',$reward);
                 db('wallet_bill')->insert(['uid'=>$now_house['uid2'],'count'=>$reward,'type'=>2,'category_id'=>7,'create_time'=>time()]);
                 }
                 $this->send1($k,$ar,$key);
    
                 }
                }else{*/
                $now_house = db('question_house')->where('id',$house_id)->find();
                $ar['house'] = $now_house;
                $log = db('question_log')->where('id',$log['id'])->find();
                $ar['question_log'] = db('question_log')->where('id',$log['id'])->find();
                $uid1 = db('member')->where('id',$house['uid1'])->field('id,nickname,head')->find();
                $uid2 = db('member')->where('id',$house['uid2'])->field('id,nickname,head')->find();
                $ar['uid1'] = $uid1;
                $ar['uid2'] = $uid2;
                $this->send1($k,$ar,$key,$connection);
                // }
    
            }
        }
    }
    function scroe($now,$time,$sort){
        $score = ($sort==10)?200:100;
        $len = $now-$time;
        $len  = ($len>10)?10:$len;
        $a = [1,1,0.9,0.9,0.8,0.8,0.8,0.6,0.6,0.5,0.5];
        return $score*$a[$len];
    }
    function play_in($k,$ar,$connection){
        $uid = $ar['uid'];
        $grades = array('easy'=>1,'normal'=>2,'hard'=>3);
        $grade = $ar['grade'];
        if(empty($uid)){
            exit;
        }
        $check = db('question_house')->where('status',0)->where("(uid1=$uid or uid2=$uid)")->find();
        $type = 0;//还未匹配
        $key = '';
        if(!empty($check)){//还未开始
            if($check['uid2']==$uid){
                $type = 2;//已匹配
                $key = $check['uid1_key'];$ar['id'] = $check['id'];$ar['uid1'] = $check['uid1'];$ar['uid2'] = $uid;
                db('question_house')->where('id',$check['id'])->update(['uid2_key'=>$k]);
            }elseif(!empty($check['uid2'])){
                $type = 1;//已匹配
                db('question_house')->where('id',$check['id'])->update(['uid1_key'=>$k]);
                $key = $check['uid2_key'];$ar['id'] = $check['id'];$ar['uid1'] = $uid;$ar['uid2'] = $check['uid2'];
            }
    
        }else{//已经开始
            $check = db('question_house')->where('status',1)->where("(uid1=$uid or uid2=$uid)")->find();
            if(!empty($check)){
                if($check['uid1']==$uid){
                    $type = 3;//已匹配
                    db('question_house')->where('id',$check['id'])->update(['uid1_key'=>$k]);
                    $key = $check['uid2_key'];$ar['id'] = $check['id'];$ar['uid1'] = $uid;$ar['uid2'] = $check['uid2'];
                }elseif($check['uid2']==$uid){
                    $type = 3;//已匹配
                    db('question_house')->where('id',$check['id'])->update(['uid2_key'=>$k]);
                    $key = $check['uid1_key'];$ar['id'] = $check['id'];$ar['uid1'] = $check['uid1'];$ar['uid2'] = $uid;
                }
            }
        }
        if($type==0){
            $check_question = db('question')->where('grade',$grades[$grade])->count();
            if($check_question<10){
                $ar['type'] = 'play_out';
                $this->send1($k,$ar,$key,$connection);
            }else{
                $check = db('question_house')->where('status',0)->find();
                if(empty($check)){
                    $data = array(
                        'create_time'=>time(),'uid1'=>$uid,'status'=>0,'uid1_key'=>$k,'grade'=>$grades[$grade]
                    );
                    $fee = 0;
                    if($data['grade']==1){
                        $fee = db('config')->where('name','easy_out')->value('value');
                    }elseif($data['grade']==2){
                        $fee = db('config')->where('name','normal_out')->value('value');
                    }elseif($data['grade']==3){
                        $fee = db('config')->where('name','hard_out')->value('value');
                    }
                    db('member')->where('id',$uid)->setDec('lcc_wallet',$fee);
                    db('wallet_bill')->insert(['uid'=>$uid,'count'=>$fee,'type'=>1,'category_id'=>12,'create_time'=>time()]);
                    $data['out_fee'] = $fee;
                    db('question_house')->insert($data);
                }else{
                    if($check['uid1']!=$uid&&!empty($check['uid1'])){
                        $ar['id'] = $check['id'];
                        $uid1 = db('member')->where('id',$check['uid1'])->field('id,nickname,head')->find();
                        $uid2 = db('member')->where('id',$uid)->field('id,nickname,head')->find();
                        $ar['uid1'] = $uid1;
                        $ar['uid2'] = $uid2;
                        db('question_house')->where('id',$check['id'])->update(['uid2'=>$uid,'uid2_key'=>$k]);
                        db('member')->where('id',$uid)->setDec('lcc_wallet',$check['out_fee']);
                        db('wallet_bill')->insert(['uid'=>$uid,'count'=>$check['out_fee'],'type'=>1,'category_id'=>12,'create_time'=>time()]);
                        $this->send1($k,$ar,$check['uid1_key'],$connection);
                    }else{
                        $ar['id'] = $check['id'];
                        $uid1 = db('member')->where('id',$uid)->field('id,nickname,head')->find();
                        $uid2 = db('member')->where('id',$check['uid1'])->field('id,nickname,head')->find();
                        $ar['uid1'] = $uid1;
                        $ar['uid2'] = $uid2;
                        db('question_house')->where('id',$check['id'])->update(['uid1'=>$uid,'uid1_key'=>$k]);
                        db('member')->where('id',$uid)->setDec('lcc_wallet',$check['out_fee']);
                        db('wallet_bill')->insert(['uid'=>$uid,'count'=>$check['out_fee'],'type'=>1,'category_id'=>12,'create_time'=>time()]);
                        //$this->send1($k,$ar,$check['uid2_key']);
                    }
                }
            }
    
        }else{
            if($type==3){
                $ar['type'] = 'play';
            }
            $uid1 = db('member')->where('id',$ar['uid1'])->field('id,nickname,head')->find();
            $uid2 = db('member')->where('id',$ar['uid2'])->field('id,nickname,head')->find();
            $ar['uid1'] = $uid1;
            $ar['uid2'] = $uid2;
            //db('socket')->insert(['name'=>json_encode($ar),'value'=>$key.'|'.$k]);
            $this->send1($k,$ar,$key,$connection);
        }
         
    }
     
    //对新加入的client推送已经在线的client
    function getusers(){
        $ar=array();
        foreach($this->users as $k=>$v){
            $ar[]=array('code'=>$k,'name'=>$v['name']);
        }
        return $ar;
    }
     
    //$k 发信息人的socketID $key接受人的 socketID ，根据这个socketID可以查找相应的client进行消息推送，即指定client进行发送
    function send11($k,$ar,$key=''){
        $ar['code1']=$key;
        $ar['code']=$k;
        $ar['time']=date('m-d H:i:s');
        //对发送信息进行编码处理
        $str = $this->code(json_encode($ar));
        //面对大家即所有在线者发送信息
        if($key=='all'){
            $users=$this->users;
            //如果是add表示新加的client
            if($ar['type']=='add'){
                $ar['type']='madd';
                $ar['users']=$this->getusers();        //取出所有在线者，用于显示在在线用户列表中
                $str1 = $this->code(json_encode($ar)); //单独对新client进行编码处理，数据不一样
                //对新client自己单独发送，因为有些数据是不一样的
                @socket_write($users[$k]['socket'],$str1,strlen($str1));
                //上面已经对client自己单独发送的，后面就无需再次发送，故unset
                unset($users[$k]);
            }
            //除了新client外，对其他client进行发送信息。数据量大时，就要考虑延时等问题了
            foreach($users as $v){
                @socket_write($v['socket'],$str,strlen($str));
            }
        }else if($key){
            //单独对个人发送信息，即双方聊天
            @socket_write($this->users[$k]['socket'],$str,strlen($str));
            @socket_write($this->users[$key]['socket'],$str,strlen($str));
        }else{
            @socket_write($this->users[$k]['socket'],$str,strlen($str));
        }
        //data: "{"type":"madd","name":"\u51c6\u5907\u4e0b\u5355\u4e86","code1":"all","code":"5bc6f62fb5cd9","time":"10-17 16:43:27","users":[{"code":"5bc6f62fb5cd9","name":"\u51c6\u5907\u4e0b\u5355\u4e86"}]}"
    }
     
    //用户退出向所用client推送信息
    function send2($k){
        $this->close($k);
        $ar['type']='rmove';
        $ar['nrong']=$k;
        $this->send1(false,$ar);
    }
     
    //记录日志
    function e($str){
        $path=dirname(__FILE__).'/log.txt';
        $str=$str."\n";
        @file_put_contents($path, $str,FILE_APPEND);
        //error_log($str,3,$path);
        //编码处理
        //echo iconv('utf-8','gbk//IGNORE',$str);
    }
    function import($k,$ar){
    
        $excelpath = $_SERVER['DOCUMENT_ROOT'].'/excel/'.$ar['excel_name'].'.xlsx';
        if(file_exists($excelpath)){
            //db('socket')->insert(['name'=>'AAAABBB','value'=>json_encode($ar)]);
            Vendor('phpexcel.PHPExcel');//调用类库,路径是基于vendor文件夹的
            Vendor('phpexcel.PHPExcel.Worksheet.Drawing');
            Vendor('phpexcel.PHPExcel.Writer.Excel2007');
            $objExcel = new \PHPExcel();
            //set document Property
            $objWriter = \PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objWriter->load ( $excelpath );
            $sheet = $objPHPExcel->getSheet ( 0 );
            $rows = $sheet->getHighestRow (); // 取得总行数
            // 数据处理
            $datas = array ();
            $delete_row = array ();
            $excel = array ();
            $is_download = false;
            //正确和错误条数计数
            $add_num = 0;
            $edit_num = 0;
            $error_num = 0;
            //当前执行位置
            $now_run = 1;
            $percent = 0;
            for($i = 2; $i <= $rows; $i ++) {
                $flag = false;
                $cs_name = '';
                $now_run++;
                $percent = intval(($now_run/$rows)*100);
                $error_msg = '';$question = [];$excel = [];
                // 名称<必填>
                $excel ['content'] = $objPHPExcel->getActiveSheet ()->getCell ( "A{$i}" )->getValue ();
                if (empty( $excel ['content'] )) {
                    $flag = true;
                    $error_msg = !!$error_msg ? $error_msg."、题目为必填" : $error_msg.'题目为必填';
                }
                //答案
                $question[1] = $objPHPExcel->getActiveSheet ()->getCell ( "B{$i}" )->getValue ();
                if (empty( $question[1] )) {
                    $flag = true;
                    $error_msg = !!$error_msg ? $error_msg."、选项A为必填" : $error_msg.'选项A为必填';
                }
                $question[2] = $objPHPExcel->getActiveSheet ()->getCell ( "C{$i}" )->getValue ();
                if (empty( $question[2] )) {
                    $flag = true;
                    $error_msg = !!$error_msg ? $error_msg."、选项B为必填" : $error_msg.'选项B为必填';
                }
                $question[3] = $objPHPExcel->getActiveSheet ()->getCell ( "D{$i}" )->getValue ();
                if (empty( $question[3] )) {
                    $flag = true;
                    $error_msg = !!$error_msg ? $error_msg."、选项C为必填" : $error_msg.'选项C为必填';
                }
                $question[4] = $objPHPExcel->getActiveSheet ()->getCell ( "E{$i}" )->getValue ();
                if (empty( $question[4] )) {
                    $flag = true;
                    $error_msg = !!$error_msg ? $error_msg."、选项D为必填" : $error_msg.'选项D为必填';
                }
                $excel ['answer'] = $objPHPExcel->getActiveSheet ()->getCell ( "F{$i}" )->getValue ();
                if (empty( $excel ['answer'] )) {
                    $flag = true;
                    $error_msg = !!$error_msg ? $error_msg."、答案为必填" : $error_msg.'答案为必填';
                }
                $excel ['type'] = $objPHPExcel->getActiveSheet ()->getCell ( "G{$i}" )->getValue ();
                $excel ['type'] = empty(trim($excel ['type']))?0:trim($excel ['type']);
                $excel ['grade'] = $objPHPExcel->getActiveSheet ()->getCell ( "H{$i}" )->getValue ();
                $excel ['grade'] = empty(trim($excel ['grade']))?1:trim($excel ['grade']);
                if (! $flag) {
                    // 保存数据
                    $excel ['question'] = serialize($question);
                    $excel ['create_time'] = time();
                    $result = db('question')->insert($excel);
                    $add_num++;
                    unset($excel);
                    $delete_row [] = $i; // 记录插入成功的当前行
    
                } else { // 有错误的EXCEL行
                    $is_download = true;
                    $objPHPExcel->getActiveSheet()->setCellValue("I{$i}",$error_msg);
                    $error_num++;
                    unset($excel);
                }
                $ar['percent'] = $percent;$ar['status'] = false;$ar['error'] = false;$ar['error_over'] = false;
                $ar['total'] = $rows-1;
                $ar['add'] = $add_num;
                $ar['error_num'] = $error_num;
                $this->send1($k,$ar,'',$connection);
            }
            $ar['status'] = true;
            // 如有错误下载错误的文件
            if ($is_download) { // 存在格式不成功excel，下载
                $ar['error'] = true;
                $this->send1($k,$ar,'',$connection);
                $ar['error'] = false;
                $delete_row = array_reverse ( $delete_row );
                /* foreach ( $delete_row as $v ) {
                 $objPHPExcel->getActiveSheet ()->removeRow ( $v );
                } */
    
                // 删除原EXCEL文件
                if (file_exists ( $excelpath )) {
                    unlink ( $excelpath );
                }
                $objPHPExcel->getActiveSheet()->setCellValue("I1",'错误信息');
                $filenames = 'import_error' . date ( 'YmdHis' );
                $filename = $_SERVER['DOCUMENT_ROOT'].'/excel/'.$filenames.'.xlsx';
                $filename = str_replace('\\', '/', trim($filename));
                $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                $objWriter->save ($filename);
                 
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
                $download_error = $http_type.$_SERVER['HTTP_HOST'].'/excel/'.$filenames.'.xlsx';;
                $ar['error_over'] = $download_error;
                $this->send1($k,$ar,'',$connection);
            }
        }
    
         
    }
    

}
?>